<template>
  <div class="comment-list-wrap">
    <van-cell title="全部评论"></van-cell>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <comment-item
        v-for="(item, index) in list"
        :key="index"
        :comment="item"
      />
    </van-list>
  </div>
</template>

<script>
import { getComments } from "@/api/comment";
import CommentItem from "./comment-item";
export default {
  name: "CommentList",
  props: {
    source: {
      type: [Number, String, Object],
      required: true,
    },
    list: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  components: {
    CommentItem,
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      offset: null, // 获取下一页数据的页码
      limit: 10, // 每页大小
    };
  },
  created() {
    this.onLoad();
  },
  methods: {
    async onLoad() {
      //   1. 请求获取数据
      const { data } = await getComments({
        type: "a",
        source: Number(this.source),
        offset: this.offset,
        limit: this.limit,
      });
      //   2. 把数据放到列表中
      const { results } = data.data;
      this.list.push(...results);
      this.$emit("total-count", data.data.total_count);
      //   3. 将本次的loading 关闭
      this.loading = false;
      //   4. 判断是否还有数据
      if (results.length) {
        //   如果有，更新获取下一页数据的页码
        this.offset = data.data.last_id;
      } else {
        // 如果没有， 则将finished 设置为true，不再触发加载更多了
        this.finished = true;
      }
    },
  },
};
</script>

<style>
</style>
